#include <generik/tracing.h>
GENERIK_TRACER_GLOBAL;

/** \file client.cc
An example of a simple telnet socket client.
It uses the generik::socket  and generik::socketstream libraries.
*/

#include <iostream>
#include <generik/socketstream.h>

int main(int argc, char** argv)
{
	GENERIK_TRACER;

	// default destination is LOCALHOST:4756
	std::string server = generik::socket::LOCALHOST;
	int port = 4756;
	
	if (argc > 1)
	{
		// the user has specified a different port
		std::stringstream conv;
		conv<<argv[2];
		conv>>port;
	}
	if (argc > 2)
	{
		// the user has specified a different server
		server = argv[1];
	}
	GENERIK_TRACE("using "<<server<<":"<<port);
	
	// open a socket stream to the server's port
	generik::socketstream ss(port, server);
	if (!ss.is_open())
	{
		GENERIK_ERROR("could not open "<<server<<":"<<port);
		exit(-1);
	}

	// read line by line from STDIN
	std::string input;
	std::getline(std::cin, input);
	while (!std::cin.eof())
	{
		// send each line to the socket stream
		GENERIK_TRACE("sending ["<<input<<"]: "<<input.length());
		ss<<input;
		//  have to send a newline and flush, otherwise we will never get a reply!
		ss<<std::endl;
		
		GENERIK_TRACE("waiting for reply");
		
		// read the reply
		std::string output;
		std::getline(ss, output);
		if (ss.eof())
		{
			// if the connection was closed, exit cleanly
			GENERIK_TRACE("connection terminated");
			break;
		}
		std::cout<<output<<std::endl;
		
		// rinse and repeat
		std::getline(std::cin, input);
	}

	return 0;
}

